// 修复 characters 表中超过转职等级上限的数据
// 规则：未转≤100，1转≤120，2转≤140，3转及以上≤160；超出则降到上限并将 exp 置为 0

const mysql = require('mysql2/promise');
const config = require('./database-config.js');

function getLevelCap(trans) {
    if (!trans || trans <= 0) return 100;
    if (trans === 1) return 120;
    if (trans === 2) return 140;
    return 160; // 3转及以上
}

async function main() {
    const conn = await mysql.createConnection(config.source);
    try {
        console.log('🔧 开始修复角色等级上限数据...');

        // 查询所有超出上限的角色
        const [rows] = await conn.execute(
            'SELECT id, name, trans, lvl, exp FROM characters WHERE (trans = 0 AND lvl > 100) OR (trans = 1 AND lvl > 120) OR (trans = 2 AND lvl > 140) OR (trans >= 3 AND lvl > 160)'
        );

        if (!rows || rows.length === 0) {
            console.log('✅ 没有发现超出上限的数据');
            return;
        }

        console.log(`📋 发现 ${rows.length} 条超出上限的数据，开始修复...`);

        let fixedCount = 0;
        for (const row of rows) {
            const cap = getLevelCap(row.trans || 0);
            const newLvl = cap;
            const newExp = 0; // 上限时设为0，表示无下一等级
            await conn.execute('UPDATE characters SET lvl = ?, exp = ?, updated_at = NOW() WHERE id = ?', [newLvl, newExp, row.id]);
            fixedCount += 1;
            console.log(`➡️  修复角色ID=${row.id}, 名称=${row.name}, trans=${row.trans}, lvl: ${row.lvl} -> ${newLvl}, exp: ${row.exp} -> ${newExp}`);
        }

        console.log(`✅ 修复完成，共修复 ${fixedCount} 条记录。`);
    } catch (err) {
        console.error('❌ 修复失败:', err.message || err);
        process.exitCode = 1;
    } finally {
        await conn.end();
    }
}

if (require.main === module) {
    main();
}


